import React, { useState, useEffect } from 'react';
import { bannerApi } from '../services/api';

interface Banner {
  id: number;
  title: string;
  image: string;
  link: string;
  sort: number;
  status: 'active' | 'inactive';
  createTime: string;
}

const BannerList: React.FC = () => {
  const [banners, setBanners] = useState<Banner[]>([]);
  const [currentPage, setCurrentPage] = useState(1);
  const [pageSize] = useState(10);
  const [total, setTotal] = useState(0);
  const [showModal, setShowModal] = useState(false);
  const [editingBanner, setEditingBanner] = useState<Banner | null>(null);
  const [formData, setFormData] = useState({
    title: '',
    image: '',
    link: '',
    sort: '',
    status: 'active' as 'active' | 'inactive'
  });

  // 模拟数据
  useEffect(() => {
    // 调用API获取轮播图列表
    const fetchBanners = async () => {
      try {
        const response: any = await bannerApi.getBanners(currentPage, pageSize);
        if (response.isSuccess && response.data) {
          setBanners(response.data);
          setTotal(response.total || 0);
        }
      } catch (error) {
        console.error('获取轮播图列表失败:', error);
        alert('获取轮播图列表失败');
      }
    };
    fetchBanners();
  }, [currentPage, pageSize]);

  const handleAdd = () => {
    setEditingBanner(null);
    setFormData({
      title: '',
      image: '',
      link: '',
      sort: '',
      status: 'active'
    });
    setShowModal(true);
  };

  const handleEdit = (banner: Banner) => {
    setEditingBanner(banner);
    setFormData({
      title: banner.title,
      image: banner.image,
      link: banner.link,
      sort: banner.sort.toString(),
      status: banner.status
    });
    setShowModal(true);
  };

  const handleDelete = async (id: number) => {
    if (window.confirm('确定要删除这个轮播图吗？')) {
      try {
        await bannerApi.deleteBanner(id);
        // 重新获取轮播图列表
        const response: any = await bannerApi.getBanners(currentPage, pageSize);
        if (response.isSuccess && response.data) {
          setBanners(response.data);
          setTotal(response.total || 0);
        }
        alert('删除成功');
      } catch (error) {
        console.error('删除轮播图失败:', error);
        alert('删除轮播图失败');
      }
    }
  };

  const handleSubmit = async () => {
    if (!formData.title || !formData.image || !formData.sort) {
      alert('请填写完整信息');
      return;
    }

    try {
      const submitData = {
        title: formData.title,
        image: formData.image,
        link: formData.link,
        sort: parseInt(formData.sort),
        status: formData.status
      };

      if (editingBanner) {
        // 编辑轮播图
        await bannerApi.updateBanner(editingBanner.id, submitData);
        alert('更新成功');
      } else {
        // 新增轮播图
        await bannerApi.createBanner(submitData);
        alert('创建成功');
      }
      
      // 重新获取轮播图列表
      const response: any = await bannerApi.getBanners(currentPage, pageSize);
      if (response.isSuccess && response.data) {
        setBanners(response.data);
        setTotal(response.total || 0);
      }
      setShowModal(false);
    } catch (error) {
      console.error('操作失败:', error);
      alert('操作失败');
    }
  };

  const totalPages = Math.ceil(total / pageSize);

  return (
    <div style={{ padding: 24 }}>
      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 24 }}>
        <h2>轮播图管理</h2>
        <button 
          onClick={handleAdd}
          style={{ padding: '8px 16px', background: '#1890ff', color: 'white', border: 'none', borderRadius: 4, cursor: 'pointer' }}
        >
          新增轮播图
        </button>
      </div>

      {/* 轮播图列表 */}
      <div style={{ background: 'white', borderRadius: 8, overflow: 'hidden', boxShadow: '0 2px 8px rgba(0,0,0,0.1)' }}>
        <table style={{ width: '100%', borderCollapse: 'collapse' }}>
          <thead>
            <tr style={{ background: '#fafafa' }}>
              <th style={{ padding: 12, textAlign: 'left', borderBottom: '1px solid #f0f0f0' }}>排序</th>
              <th style={{ padding: 12, textAlign: 'left', borderBottom: '1px solid #f0f0f0' }}>预览图</th>
              <th style={{ padding: 12, textAlign: 'left', borderBottom: '1px solid #f0f0f0' }}>标题</th>
              <th style={{ padding: 12, textAlign: 'left', borderBottom: '1px solid #f0f0f0' }}>链接</th>
              <th style={{ padding: 12, textAlign: 'left', borderBottom: '1px solid #f0f0f0' }}>状态</th>
              <th style={{ padding: 12, textAlign: 'left', borderBottom: '1px solid #f0f0f0' }}>创建时间</th>
              <th style={{ padding: 12, textAlign: 'left', borderBottom: '1px solid #f0f0f0' }}>操作</th>
            </tr>
          </thead>
          <tbody>
            {banners.map(banner => (
              <tr key={banner.id} style={{ borderBottom: '1px solid #f0f0f0' }}>
                <td style={{ padding: 12 }}>{banner.sort}</td>
                <td style={{ padding: 12 }}>
                  <img 
                    src={banner.image} 
                    alt={banner.title}
                    style={{ width: 120, height: 60, objectFit: 'cover', borderRadius: 4 }}
                  />
                </td>
                <td style={{ padding: 12, fontWeight: 'bold' }}>{banner.title}</td>
                <td style={{ padding: 12 }}>
                  <div style={{ maxWidth: 200, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>
                    {banner.link}
                  </div>
                </td>
                <td style={{ padding: 12 }}>
                  <span style={{ 
                    padding: '4px 8px', 
                    borderRadius: 4, 
                    fontSize: 12,
                    background: banner.status === 'active' ? '#f6ffed' : '#fff2e8',
                    color: banner.status === 'active' ? '#52c41a' : '#fa8c16'
                  }}>
                    {banner.status === 'active' ? '启用' : '禁用'}
                  </span>
                </td>
                <td style={{ padding: 12 }}>{banner.createTime}</td>
                <td style={{ padding: 12 }}>
                  <button 
                    onClick={() => handleEdit(banner)}
                    style={{ marginRight: 8, padding: '4px 8px', background: '#1890ff', color: 'white', border: 'none', borderRadius: 4, cursor: 'pointer', fontSize: 12 }}
                  >
                    编辑
                  </button>
                  <button 
                    onClick={() => handleDelete(banner.id)}
                    style={{ padding: '4px 8px', background: '#ff4d4f', color: 'white', border: 'none', borderRadius: 4, cursor: 'pointer', fontSize: 12 }}
                  >
                    删除
                  </button>
                </td>
              </tr>
            ))}
          </tbody>
        </table>
      </div>

      {/* 分页 */}
      <div style={{ display: 'flex', justifyContent: 'center', marginTop: 24 }}>
        <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
          <button 
            onClick={() => setCurrentPage(prev => Math.max(1, prev - 1))}
            disabled={currentPage === 1}
            style={{ 
              padding: '8px 12px', 
              background: currentPage === 1 ? '#f5f5f5' : '#1890ff', 
              color: currentPage === 1 ? '#ccc' : 'white', 
              border: 'none', 
              borderRadius: 4, 
              cursor: currentPage === 1 ? 'not-allowed' : 'pointer' 
            }}
          >
            上一页
          </button>
          <span style={{ padding: '8px 12px' }}>
            第 {currentPage} 页，共 {totalPages} 页
          </span>
          <button 
            onClick={() => setCurrentPage(prev => Math.min(totalPages, prev + 1))}
            disabled={currentPage === totalPages}
            style={{ 
              padding: '8px 12px', 
              background: currentPage === totalPages ? '#f5f5f5' : '#1890ff', 
              color: currentPage === totalPages ? '#ccc' : 'white', 
              border: 'none', 
              borderRadius: 4, 
              cursor: currentPage === totalPages ? 'not-allowed' : 'pointer' 
            }}
          >
            下一页
          </button>
        </div>
      </div>

      {/* 新增/编辑模态框 */}
      {showModal && (
        <div style={{
          position: 'fixed',
          top: 0,
          left: 0,
          right: 0,
          bottom: 0,
          background: 'rgba(0,0,0,0.5)',
          display: 'flex',
          alignItems: 'center',
          justifyContent: 'center',
          zIndex: 1000
        }}>
          <div style={{
            background: 'white',
            padding: 24,
            borderRadius: 8,
            width: 500,
            maxWidth: '90vw',
            maxHeight: '90vh',
            overflowY: 'auto'
          }}>
            <h3 style={{ marginTop: 0, marginBottom: 24 }}>
              {editingBanner ? '编辑轮播图' : '新增轮播图'}
            </h3>
            <div style={{ marginBottom: 16 }}>
              <label style={{ display: 'block', marginBottom: 8 }}>标题：</label>
              <input
                type="text"
                value={formData.title}
                onChange={(e) => setFormData({...formData, title: e.target.value})}
                style={{ width: '100%', padding: 8, border: '1px solid #d9d9d9', borderRadius: 4 }}
                placeholder="请输入轮播图标题"
              />
            </div>
            <div style={{ marginBottom: 16 }}>
              <label style={{ display: 'block', marginBottom: 8 }}>图片URL：</label>
              <input
                type="text"
                value={formData.image}
                onChange={(e) => setFormData({...formData, image: e.target.value})}
                style={{ width: '100%', padding: 8, border: '1px solid #d9d9d9', borderRadius: 4 }}
                placeholder="请输入图片URL"
              />
              {formData.image && (
                <div style={{ marginTop: 8 }}>
                  <img 
                    src={formData.image} 
                    alt="预览"
                    style={{ width: '100%', maxHeight: 200, objectFit: 'cover', borderRadius: 4 }}
                    onError={(e) => {
                      e.currentTarget.style.display = 'none';
                    }}
                  />
                </div>
              )}
            </div>
            <div style={{ marginBottom: 16 }}>
              <label style={{ display: 'block', marginBottom: 8 }}>链接地址：</label>
              <input
                type="text"
                value={formData.link}
                onChange={(e) => setFormData({...formData, link: e.target.value})}
                style={{ width: '100%', padding: 8, border: '1px solid #d9d9d9', borderRadius: 4 }}
                placeholder="请输入链接地址"
              />
            </div>
            <div style={{ marginBottom: 16 }}>
              <label style={{ display: 'block', marginBottom: 8 }}>排序：</label>
              <input
                type="number"
                value={formData.sort}
                onChange={(e) => setFormData({...formData, sort: e.target.value})}
                style={{ width: '100%', padding: 8, border: '1px solid #d9d9d9', borderRadius: 4 }}
                placeholder="请输入排序号"
              />
            </div>
            <div style={{ marginBottom: 24 }}>
              <label style={{ display: 'block', marginBottom: 8 }}>状态：</label>
              <select
                value={formData.status}
                onChange={(e) => setFormData({...formData, status: e.target.value as 'active' | 'inactive'})}
                style={{ width: '100%', padding: 8, border: '1px solid #d9d9d9', borderRadius: 4 }}
              >
                <option value="active">启用</option>
                <option value="inactive">禁用</option>
              </select>
            </div>
            <div style={{ display: 'flex', gap: 12, justifyContent: 'flex-end' }}>
              <button
                onClick={() => setShowModal(false)}
                style={{ padding: '8px 16px', background: '#f0f0f0', border: '1px solid #d9d9d9', borderRadius: 4, cursor: 'pointer' }}
              >
                取消
              </button>
              <button
                onClick={handleSubmit}
                style={{ padding: '8px 16px', background: '#1890ff', color: 'white', border: 'none', borderRadius: 4, cursor: 'pointer' }}
              >
                确定
              </button>
            </div>
          </div>
        </div>
      )}
    </div>
  );
};

export default BannerList; 